<?php
class AdminController extends Zend_Controller_Action
{
    public function init()
    {
        $auth = Zend_Auth::getInstance ();
        if ($auth->hasIdentity ()) {
            $this->view->identity = $auth->getIdentity ();
        }
        
        $this->_helper->layout->setLayout ( 'admin' );
    }

    public function homeAction()
    {
        $adminForm = new Form_Admin_Login();
        $adminForm->setAction ( $this->_helper->url ( 'home', 'admin' ) );
        $adminForm->getElement ( 'username' )->setRequired ( FALSE );
        $adminForm->getElement ( 'password' )->setRequired ( FALSE );
        $adminForm->getElement ( 'password_confirm' )->setRequired ( FALSE );
        
        $mdlAdmins = new Model_Admin();
        
        if ($this->_request->isPost () && $adminForm->isValid ( $_POST )) {
            $data = $adminForm->getValues ();
            
            $currentAdmin = $mdlAdmins->getCurrentAdminInfor();
            if ($data ['username']) {
                $currentAdmin->username = $data ['username'];
                $currentAdmin->save ();
            }
            
            if ($data ['password']) {
                $currentAdmin->password = md5 ( $data ['password'] );
                $currentAdmin->save ();
            }
        } else {
            $currentAdmin = $mdlAdmins->getCurrentAdminInfor ()->toArray ();
            $adminForm->populate ( $currentAdmin );
        }
        
        $this->view->form = $adminForm;
    }

    public function loginAction() 
    {
    	$this->logoutAction();
    	
        $adminForm = new Form_Admin_Login();
        $adminForm->setAction ( $this->_helper->url ( 'login', 'admin' ) );
        $adminForm->removeElement ( 'password_confirm' );
        
        if ($this->_request->isPost () && $adminForm->isValid ( $_POST ))
        {
            $data = $adminForm->getValues ();
            
            //set up the auth adapter
            //get the default db adapter
            $db = Zend_Db_Table::getDefaultAdapter ();
            
            //create the auth adapter
            $authAdapter = new Zend_Auth_Adapter_DbTable ( $db, 'admins', 'username', 'password' );
            
            //set the username and password
            $authAdapter->setIdentity ( $data ['username'] );
            $authAdapter->setCredential ( md5 ( $data ['password'] ) );
            
            //authenticate
            $result = $authAdapter->authenticate ();
            if ($result->isValid ()) {
                // store the username, first and last names of the user
                $auth = Zend_Auth::getInstance ();
                $storage = $auth->getStorage ();
                $object = $authAdapter->getResultRowObject ( array ('id', 'username'));
                $object->role = 'admin';
                $storage->write ( $object );
                return $this->_redirect ( 'admin/home' );
            } else {
                $this->view->loginMessage = "Sorry, your username or password was incorrect";
            }
        }
        $this->view->form = $adminForm;
    }

    public function logoutAction()
    {
        $authAdapter = Zend_Auth::getInstance ();
        $authAdapter->clearIdentity ();
    }
    
    /*
    * DIMENTION FUNCTIONS (MANAGE, INSERT, UPDATE, DELETE)
    */
    
    public function dimensionAction()
    {
    	// fetch the news paginator adapter
    	$mdlDimension = new Model_Dimension();
    	$dimensions = $mdlDimension->getList ( null, array ("dim_value ASC" ) );
    
    	$this->view->dimensions = $dimensions;
    }
    
    public function dimensionCreateAction()
    {
    	$frmDimension = new Form_Admin_Dimension();
    
    	if ($this->getRequest ()->isPost ())
    	{
    		if ($frmDimension->isValid ( $_POST ))
    		{
    			$dimValue = $frmDimension->getValue ( 'dim_value' );
    
    			$mdlDimension = new Model_Dimension();
    			$result = $mdlDimension->createDimension($dimValue);
    			if ($result)
    			{
    				return $this->_redirect ( 'admin/dimension' );
    			}
    		}
    	}
    	$frmDimension->setAction ( $this->_helper->url ( 'dimension-create', 'admin' ) );
    	$this->view->form = $frmDimension;
    }
    
    public function dimensionUpdateAction()
    {
    	$frmDimension = new Form_Admin_Dimension();
    
    	if ($this->getRequest ()->isPost ())
    	{
    		if ($frmDimension->isValid ( $_POST ))
    		{
    			$dim_id = $frmDimension->getValue ( 'dim_id' );
    			$dimValue = $frmDimension->getValue ( 'dim_value' );
    			
    			$mdlDimension = new Model_Dimension();
    			$result = $mdlDimension->updateDimension($dim_id, $dimValue);
    
    			return $this->_redirect ( 'admin/dimension' );
    		}
    	}
    	else
    	{
    		$dim_id = $this->_request->getParam ( 'dim_id' );
   
    		$mdlDimension = new Model_Dimension();
    		$currentDimension = $mdlDimension->find ( $dim_id )->current ();
    		$frmDimension->populate ( $currentDimension->toArray () );
    	}
    	$frmDimension->setAction ( $this->_helper->url ( 'dimension-update', 'admin' ) );
    	$this->view->form = $frmDimension;
    }
    
    public function dimensionDeleteAction()
    {
    	$id = $this->_request->getParam ( 'id' );
    	$mdlDimension = new Model_Dimension();
    	try {
    		$mdlDimension->deleteDimension($id);
    	} catch(Exception $ex) {
    	}
    	return $this->_redirect ( 'admin/dimension' );
    }
    
    /*
     * CATEGORIES FUNCTIONS (MANAGE, INSERT, UPDATE, DELETE)
      */
    
    public function categoryAction()
    {
    	// fetch the news paginator adapter
    	$mdlCategory = new Model_Category();
   	 	$categories = $mdlCategory->getPaginator ( null, array ("cat_id ASC" ) );
    
    	$this->view->categories = $categories;
    }
    
    public function categoryCreateAction()
    {
    	$frmCategory = new Form_Admin_Category();
    
    	if ($this->getRequest ()->isPost ())
    	{
    		if ($frmCategory->isValid ( $_POST ))
    		{
    			$catName = $frmCategory->getValue ( 'cat_name' );
    
    			$mdlCategory = new Model_Category();
    			$result = $mdlCategory->createCategory($catName);
    			if ($result)
    			{
    				return $this->_redirect ( 'admin/category' );
    			}
    		}
    	}
    	$frmCategory->setAction ( $this->_helper->url ( 'category-create', 'admin' ) );
    	$this->view->form = $frmCategory;
    }
    
    public function categoryUpdateAction()
    {
    	$frmCategory = new Form_Admin_Category();
    
    	if ($this->getRequest ()->isPost ())
    	{
    		if ($frmCategory->isValid ( $_POST ))
    		{
    			$catID = $frmCategory->getValue ( 'cat_id' );
    			$catName = $frmCategory->getValue ( 'cat_name' );
    			 
    			$mdlCategory = new Model_Category();
    			$result = $mdlCategory->updateCategory($catID, $catName);
    
    			return $this->_redirect ( 'admin/category' );
    		}
    	}
    	else
    	{
    		$catID = $this->_request->getParam ( 'cat_id' );
    		
    		$mdlCategory = new Model_Category();
    		$currentCategory = $mdlCategory->find ( $catID )->current ();
    		$frmCategory->populate ( $currentCategory->toArray () );
    	}
    	$frmCategory->setAction ( $this->_helper->url ( 'category-update', 'admin' ) );
    	$this->view->form = $frmCategory;
    }
    
    public function categoryDeleteAction()
    {
    	$id = $this->_request->getParam ( 'id' );
    	$mdlDimension = new Model_Dimension();
    	try {
    		$mdlDimension->deleteDimension($id);
    	} catch(Exception $ex) {
    	}
    	return $this->_redirect ( 'admin/category' );
    }
    
    
    /*
     * PRODUCTS FUNCTIONS (MANAGE, INSERT, UPDATE, DELETE)
      */
    
    public function productAction()
    {
    	$catID = $this->_request->getParam ( 'cat_id', null );
    	$dimID = $this->_request->getParam ( 'dim_id', null );
    	
    	$where = array();
    	
   	 	if($catID) {
    		$where['cat_id = ?'] = $catID;
    	}
    	
    	if($dimID) {
    		$where['dim_id = ?'] = $dimID;
    	}
    	
    	$this->view->catID = $catID;
    	$this->view->dimID = $dimID;
    	
    	// fetch the news paginator adapter
    	$mdlProduct = new Model_Product();
    	$paginator = $mdlProduct->getPaginator ( $where, array ("product_id DESC" ), $this->_request->getParam ( 'page', 1 ), 10 );
    	$this->view->paginator = $paginator;
    	
    	$mdlDimension = new Model_Dimension();
    	$dimensions = $mdlDimension->getList ( null, array ("dim_value ASC" ) );
    	$this->view->dimensions = $dimensions;
    	
    	$mdlCategory = new Model_Category();
    	$categories = $mdlCategory->getPaginator ( null, array ("cat_id ASC" ) );
    	$this->view->categories = $categories;
    }
    
    public function productCreateAction()
    {
    	$frmProduct = new Form_Admin_Product();
    	
    	$frmProduct->initalizeImages($this->getFrontController()->getBaseUrl());
    	
    	$mdlDimension = new Model_Dimension();
    	$frmProduct->importDimensionLst($mdlDimension->getList(null, 'dim_id asc')->toArray());
    	
    	$mdlCategory = new Model_Category();
    	$frmProduct->importCategoryLst($mdlCategory->getList()->toArray());
    	 
    	$frmProduct->importSubmitButton();
    	
    	if ($this->getRequest ()->isPost ())
    	{
    		if ($frmProduct->isValid ( $_POST ))
    		{
    			$name = $frmProduct->getValue ( 'name' );
    			$dimID = $frmProduct->getValue ( 'dim_id' );
    			$catID = $frmProduct->getValue ( 'cat_id' );
    			$color = $frmProduct->getValue ( 'color' );
    			$price = $frmProduct->getValue ( 'price' );
    			$quantity = $frmProduct->getValue ( 'quantity' );
    			$description = $frmProduct->getValue ( 'description' );
    			
    			
    			$mainImage = CMS_Upload::uploadProductImages ( $frmProduct->getElement ( 'main_image' ) );
    
    			$mdlProduct = new Model_Product();
    			$result = $mdlProduct->createProduct($name, $dimID, $catID, $color, $price, $quantity, $description, $mainImage);
    			
    			if ($result)
    			{
    				for($i = 1; $i <= 3; $i ++)
    				{
    					$mdlProductImage = new Model_Image();
	    				$subImages = $frmProduct->getElement ( 'subImages' . $i );
	    				if ($subImages->isUploaded ())
	    				{
	    					$mdlProductImage->createProjectImage ( $result, CMS_Upload::uploadProductImages ( $subImages ) );
	    				}
    				}
    				
    				return $this->_redirect ( 'admin/product' );
    			}
    		}
    	}
    	$frmProduct->setAction ( $this->_helper->url ( 'product-create', 'admin' ) );
    	$this->view->form = $frmProduct;
    }
    
    public function productUpdateAction()
    {
    	$frmProduct = new Form_Admin_Product();
    
    	$frmProduct->initalizeImages($this->getFrontController()->getBaseUrl());
    	
    	$mdlDimension = new Model_Dimension();
    	$frmProduct->importDimensionLst($mdlDimension->getList()->toArray());
    	 
    	$mdlCategory = new Model_Category();
    	$frmProduct->importCategoryLst($mdlCategory->getList()->toArray());
    	
    	$frmProduct->importSubmitButton();
    	
    	if ($this->getRequest ()->isPost ())
    	{
    		if ($frmProduct->isValid ( $_POST ))
    		{
    			$productID = $frmProduct->getValue ( 'product_id' );
    			$name = $frmProduct->getValue ( 'name' );
    			$dimID = $frmProduct->getValue ( 'dim_id' );
    			$catID = $frmProduct->getValue ( 'cat_id' );
    			$color = $frmProduct->getValue ( 'color' );
    			$price = $frmProduct->getValue ( 'price' );
    			$quantity = $frmProduct->getValue ( 'quantity' );
    			$description = $frmProduct->getValue ( 'description' );
    			
    			
    			$mainImage = CMS_Upload::uploadProductImages ( $frmProduct->getElement ( 'main_image' ) );
    
    			$mdlProduct = new Model_Product();
    			$result = $mdlProduct->updateProduct($productID, $name, $dimID, $catID, $color, $price, $quantity, $description, $mainImage);
    			if ($result)
    			{
    				$mdlProductImage = new Model_Image();
    				$subImagesRows = $mdlProductImage->getList ( array ('product_id = ?' => $productID ), 'product_id asc', 1, 3 )->toArray();
    				for($i = 1; $i <= 3; $i ++)
    				{
    					$subImages = $frmProduct->getElement ( 'subImages' . $i ); 
    					if (!$subImages->isUploaded ()) {
    						continue;
    					}
    					
    					if(isset($subImagesRows[$i - 1])){
	    					$mdlProductImage->updateProductImage ( $subImagesRows[$i - 1]['img_id'], $productID, CMS_Upload::uploadProductImages ( $subImages ) );
    					} else {
    						$mdlProductImage->createProjectImage ( $productID, CMS_Upload::uploadProductImages ( $subImages ) );
    					}
    				}
    				
    				return $this->_redirect ( 'admin/product' );
    			}
    		}
    	}
    	
    	$productID = $this->_request->getParam ( 'product_id' );
  
    	$mdlProduct = new Model_Product();
    	$currentProduct = $mdlProduct->find ( $productID )->current ();    	
    	$frmProduct->populate ( $currentProduct->toArray () );
    	$frmProduct->showImage ( $this->getFrontController()->getBaseUrl(), $currentProduct->main_image );

    	$mdlProductImage = new Model_Image();
    	$subImagesRows = $mdlProductImage->getList ( array ('product_id = ?' => $productID ), 'product_id asc', 1, 3 )->toArray();
    	$frmProduct->showSubImages ( $this->getFrontController()->getBaseUrl(), $subImagesRows );
    	
    	$frmProduct->setAction ( $this->_helper->url ( 'product-update', 'admin' ) );
    	$this->view->form = $frmProduct;
    }
    
    public function productDeleteAction()
    {
    	$id = $this->_request->getParam ( 'id' );
    	$mdlProduct = new Model_Product();
    	try {
    		$mdlProduct->deleteProduct($id);
    	} catch(Exception $ex) {
    	}
    	return $this->_redirect ( 'admin/product' );
    }
    
    
    /*
    * MEMBERS FUNCTIONS (MANAGE, INSERT, UPDATE, DELETE)
    */
    
    public function memberAction()
    {
    	// fetch the news paginator adapter
    	$mdlMember = new Model_Member();
    	$paginator = $mdlMember->getPaginator ( null, array ("id ASC" ), $this->_request->getParam ( 'page', 1 ), 30 );
    
    	$this->view->paginator = $paginator;
    }
    
    /*
    * ORDERS FUNCTIONS (MANAGE, INSERT, UPDATE, DELETE)
    */
    
    public function orderAction()
    {
    	$orderID = $this->_request->getParam ( 'order_id', null );
    	$fullname = $this->_request->getParam ( 'fullname', null );
    	$date = $this->_request->getParam ( 'date', null );
    	 
    	$mdlOrder = new Model_Order();
    	$oders = $mdlOrder->getManageOrders($orderID, $fullname, $date);
    
    	$this->view->orderID = $orderID;
    	$this->view->fullname = $fullname;
    	$this->view->date = $date;
    	$this->view->listOrders = $oders;
    }
    
    public function orderDetailAction()
    {
    	$orderID = $this->_request->getParam ( 'order_id' );
    	
    	$mdlOrder = new Model_Order();
    	$details = $mdlOrder->getOrderDetails($orderID);
    	$this->view->details = $details;
    }
    
    public function orderDeleteAction()
    {
    	$id = $this->_request->getParam ( 'order_id' );
    	
    	$mdlOrder = new Model_Order();
    	try {
    		$oders = $mdlOrder->deleteOrder($id);
    	} catch(Exception $ex) {
    	}
    	
    	return $this->_redirect ( 'admin/order' );
    }
}